package api;

import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @description: 删除文章
 * @author: chengbaiyi
 * @create: 2022-05-22 20:27
 */
@WebServlet("/delart")
public class DelArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知错误";
        int data = 0;
        // 验证登录状态，并且要验证归属人（只能自己删除自己的文章）
        UserInfo userInfo = SessionUtils.getLoginUser(req);
        int uid = Integer.parseInt(req.getParameter("uid"));
        if (userInfo != null && userInfo.getUid() == uid) {
            Integer aid = null;
            try {
                aid = Integer.valueOf(req.getParameter("aid"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (aid != null && aid > 0) {
                // 删除文章
                Connection connection = DBUtils.getConnection();
                String sql = "delete from article where aid=?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1, aid);
                data = statement.executeUpdate();
                msg = "";
                DBUtils.close(null, statement, connection);
            } else {
                msg = "参数非法！";
            }
        } else {
            msg = "请先登录！";
        }

        // 将结果返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200, data, msg)));
    }
}
